package com.ujoku.controller.admin;

import com.labillusion.core.platform.crypto.MD5;
import com.labillusion.core.platform.exception.UserAuthorizationException;
import com.labillusion.core.platform.web.rest.RESTController;
import com.ujoku.domain.admin.User;

import com.ujoku.request.admin.LoginForm;
import com.ujoku.service.admin.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 14-11-1.
 */
@Controller
public class UserController extends RESTController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/uj-admin/login", method = RequestMethod.POST)
    @ResponseBody
    public String doLogin(@Valid @RequestBody LoginForm form, HttpServletRequest request) {
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("name",form.getName());
        User user = (User) userService.selectOne(query);
        if(user == null || !MD5.encrypt(user.getId() + form.getPassword()).equals(user.getPassword()))
            throw new UserAuthorizationException(resources.getMessage("admin.login.failed"));

        request.getSession().setAttribute("user",user);
        return "Successfully";
    }


    @RequestMapping(value = "/uj-admin/logout", method = RequestMethod.GET)
    @ResponseBody
    public String doLogout(HttpServletRequest request) {

        request.getSession().invalidate();

        return "Successfully";
    }



}
